package util;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by kk on 2017/8/23.
 * 编码工具类
 */
public class BMUtil {
    /**
     * 根据系统时间自定义编码方式
     * @param bm 手动输入的编码
     * @param number 手动输入的数字序号
     * @return 编码序号 编码序号 字母+年+月+日+序号如 KH170823315
     */
    public static String getBM(String bm, int number){
        String num = String.valueOf(number);
        String numStr = (num.length() == 3) ? num : (num.length() == 2) ? "0" + num : "00" + num;
        return bm + getSystemDate() + numStr;
    }
    /**
     * 获取编码工具类
     * @param bmStr
     * @return 编码序号 字母+年+月+日+序号如 KH170823315
     */
    public static String getBM(String bmStr){
        if(null != bmStr && "" != bmStr) {
            String numStr = null;
            String strYYMMDD = null;
            String strBM = getBMStr(bmStr);
            String systemDate = getSystemDate();
            String bmDate = getYYMMdd(bmStr);
            if (systemDate.equals(bmDate)) {
                numStr = addNumber1(bmStr);
                strYYMMDD = bmDate;
            } else {
                numStr = "001";
                strYYMMDD = systemDate;
            }
            return strBM + strYYMMDD + numStr;
        }
        return null;
    }
    //获取传递的编码的年月日
    private static String getYYMMdd(String str){
        String string = str.substring(str.length() -9, str.length() -3);
        return string;
    }
    //正则获取字母
    private static String getBMStr(String str){
        return str.replaceAll("\\d","").trim();
    }
    //编码加1
    private static String addNumber1(String numStr){
        String numString = numStr.substring(numStr.length()-3);
        int num = Integer.parseInt(numString) + 1;
        String nStr = String.valueOf(num);
        return nStr.length() == 3 ? nStr : (nStr.length() == 2 ? "0" +nStr : "00" + nStr);
    }
    //获取系统时间并拼接成 yyMMdd
    private static String getSystemDate(){
        Calendar now = Calendar.getInstance();
        String yearStr = String.valueOf(now.get(Calendar.YEAR));
        String yearLast = yearStr.substring(2);//获取最后两位年份
        String monthStr = String.valueOf(now.get(Calendar.MONTH) + 1);
        String month = monthStr.length()==2 ? monthStr: 0 + monthStr;//获取月份
        String day = String.valueOf(now.get(Calendar.DAY_OF_MONTH));//获取日
        return yearLast + month + day;
    }
}
